import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Menu, message, Modal } from 'antd';
import React, { useState, useRef, useCallback } from 'react';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { getMsmTable, addData, handleUpdateData, changeStatus, removeData } from './service';
import styles from './index.less';
import AuthComponent from '@/components/Authorized/AuthComponent';

const { confirm } =Modal


const TableList = () => {
  const [createModalVisible, handleCreateModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [updateData, saveUpdateData] = useState({})

  const [selectedRowKeys, handleSelectedRowKeys] = useState([]) // 勾选索引
  const [selectedRows, handleSelectedRows] = useState([]) // 勾选列
  const actionRef = useRef();

  const height = document.body.clientHeight - 286.5; // 表格高度自适应

  const columns = [
    {
      title: '模板名称',
      dataIndex: 'templateName',
      width: 160,
      ellipsis:true,
    },
    {
      title: '模板编码',
      dataIndex: 'templateCode',
      width:120
    },
    {
      title: '短信内容',
      dataIndex: 'templateContent',
      width: 200,
      ellipsis: true,
    },
    {
      title: '短信模板业务类别',
      dataIndex: 'templateBusinessType',
      width: 180
    },
    {
      title: '短信模板类别',
      dataIndex: 'templateType',
      width: 130,
      valueEnum: {
        '0': {
          text: '手动',
        },
        '1': {
          text: '自动',
        }
      }
    },
    {
      title: '状态',
      dataIndex: 'state',
      width: 90,
      valueEnum: {
        '0': {
          text: '启用',
          status: 'Success'
        },
        '1': {
          text: '停用',
          status: 'Error'
        }
      }
    },
  ];

  // 新增保存
  const handleAdd = async fields => {
    const hide = message.loading('正在添加');
    try {
      let res = await addData({...fields});
      if (res.code === '0') {
        hide();
        message.success('添加成功');
        return true
      } else {
        hide()
      }
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  };

  // 编辑保存
  const handleUpdate = async fields => {
    const hide = message.loading('正在更新');
    try {
      let res = await handleUpdateData({
        id: fields.id,
        templateName: fields.templateName,
        templateContent: fields.templateContent,
        state: fields.state,
        templateCode: fields.templateCode,
        templateType: fields.templateType
      });
      if (res.code === '0') {
        hide();
        message.success('更新成功');
        return true
      } else {
        hide()
      }
    } catch (error) {
      hide();
      message.error('更新失败请重试！');
      return false;
    }
  };

  // 启用停用
  const handleOnOff = async (selectedRows, status, text) => {
      try {
        await changeStatus({
          id: selectedRows.map(row => row.id).toString(),
          state: status
        });
        message.success(`${text}成功，即将刷新`);
        return true;
      } catch (error) {
        message.error(`${text}失败，请重试`);
        return false;
      }
  };

  const tableSelectChange = (selectedRowKeys, selectedRows) =>{
    handleSelectedRowKeys(selectedRowKeys)
    handleSelectedRows(selectedRows)
  }

  const rowSelection = {
    selectedRowKeys,
    onChange: tableSelectChange
  };

  return (
    <div>
      <ProTable
        headerTitle="短信模板设置"
        className={ `${styles.msgSettingTable} rest-pro-table-form-compact`}
        actionRef={actionRef}
        options={{density: false,fullScreen:true, reload:false, setting:true}}
        rowKey="id"
        size='small'
        scroll={{ y: height}}
        toolBarRender={(action, { selectedRows }) => [
          <Button icon='plus' type="primary" onClick={() => handleCreateModalVisible(true)}>
            新建
          </Button>,
          <Button icon='edit' onClick={() => {
            if (selectedRowKeys.length > 1) {
              message.error('只能选择一条进行编辑')
            } else if (selectedRowKeys.length === 0) {
              message.error('请选择编辑的条目')
            } else {
              saveUpdateData(selectedRows[0])
              handleUpdateModalVisible(true)
            }
            }}>
            编辑
          </Button>,
          <Button
            icon="check-circle"
            onClick={ () => {
              if (selectedRowKeys.length === 0) {
                message.error("请选择启用的条目")
              } else {
                confirm({
                  title: '提示',
                  content: '确认操作后该短信模板将正式生效，你还要继续吗？',
                  onOk: async () => {
                    let res = await handleOnOff(selectedRows, '0', '启用')
                    if (res) {
                      actionRef.current.reload();
                      handleSelectedRows([])
                      handleSelectedRowKeys([])
                    }
                  }
                })
              }
            }}
            selectedKeys={[]}
          >
            启用
          </Button>,
          <Button 
            icon='stop'
            style={{marginLeft: '10px'}}
            onClick={async () =>{
              if (selectedRowKeys.length === 0) {
                message.error("请选择停用的条目")
              } else {
                confirm({
                  title: '提示',
                  content: '确认操作后该短信模板将无法使用，你还要继续吗？',
                  onOk: async () => {
                    let res = await handleOnOff(selectedRows, '1', '停用')
                    if (res) {
                      actionRef.current.reload();
                      handleSelectedRows([])
                      handleSelectedRowKeys([])
                    }
                  }
                })
              }
            }}
            selectedKeys={[]}
           >
            停用
          </Button>
        ]}
        search={false}
        rowSelection={rowSelection}
        tableAlertRender={() => {
          return false;
        }}
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
        request={params => {
          return getMsmTable(params)
        }}
        columns={columns}
      />
      <CreateForm
        onSubmit={async value => {
          const success = await handleAdd(value);
          if (success) {
            handleCreateModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleCreateModalVisible(false)}
        createModalVisible={createModalVisible}
      />

      <UpdateForm
        onSubmit={async value => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalVisible(false);
            handleSelectedRows([])
            handleSelectedRowKeys([])
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleUpdateModalVisible(false)}
        updateModalVisible={updateModalVisible}
        updateData={updateData}
      />
    </div>
  );
};

export default Form.create()(TableList);
